package com.mmdccj.yugu.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mmdccj.yugu.dto.CommentDto;
import com.mmdccj.yugu.entity.Comment;
import com.mmdccj.yugu.mapper.CommentMapper;
import com.mmdccj.yugu.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: star_
 * @date: 2023-12-11 20:17
 */
@Slf4j
@Service
public class CommentServiceImpl implements CommentService {
    // 自动注入CommentMapper实例
    @Autowired
    private CommentMapper commentMapper;

    // 插入评论的方法实现
    @Override
    public void insertComment(Comment comment) {
        commentMapper.insertComment(comment);
    }

    // 查询评论的方法实现，支持分页和排序
    @Override
    public PageInfo<CommentDto> selectComments(String id, String typeId, int currentPage, int pageSize, boolean sortByLikes) {
        // 使用PageHelper进行分页
        PageHelper.startPage(currentPage, pageSize);
        // 按点赞高到低排序
        List<CommentDto> dtoList;
        if (sortByLikes) {
            dtoList = commentMapper.selectCommentsByTypeAndTypeIdDescByLikes(id, typeId);
        } else {
            dtoList = commentMapper.selectCommentsByTypeAndTypeIdAscByTime(id, typeId);
        }
        // 按最新时间排序
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < dtoList.size(); i++) {
            Integer lastId = map.get(dtoList.get(i).getId());
            if (lastId != null) {
                CommentDto comment = dtoList.get(lastId);
                if (comment.getId().equals(comment.getCommented().getId())) {
                    dtoList.remove(map.get(dtoList.get(i).getId()));
                    map.remove(dtoList.get(i).getId());
                    i--;
                    continue;
                } else {
                    comment = dtoList.get(i);
                    if (comment.getId().equals(comment.getCommented().getId())) {
                        dtoList.remove(i);
                        i--;
                        continue;
                    }
                }
            }
            map.put(dtoList.get(i).getId(), i);
        }
        return new PageInfo<>(dtoList);
    }

    // 点赞评论的方法实现，使用事务管理
    @Override
    @Transactional
    public boolean like(String userId, String commentId) {
        // 检查用户是否已经点赞过该评论
        if (commentMapper.checkLike(userId, commentId) == 0) {
            // 如果未点赞，则进行点赞操作
            Integer likes = commentMapper.like(commentId);
            // 更新评论的点赞数量
            commentMapper.updateLike(commentId, likes + 1);
            // 记录用户对评论的点赞
            commentMapper.insertLikeTo(userId, commentId);
            return true;
        } else {
            // 如果已经点赞过，则返回false
            return false;
        }
    }
}
